package com.cskaoyan.service.impl;

import com.cskaoyan.bean.data.TopicDetailData;
import com.cskaoyan.bean.data.PageData;
import com.cskaoyan.mapper.MarketGoodsMapper;
import com.cskaoyan.mapper.MarketTopicMapper;
import com.cskaoyan.model.MarketGoods;
import com.cskaoyan.model.MarketGoodsExample;
import com.cskaoyan.model.MarketTopic;
import com.cskaoyan.model.MarketTopicExample;
import com.cskaoyan.service.TopicService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class TopicServiceImpl implements TopicService {
    @Autowired
    MarketTopicMapper marketTopicMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;

    @Override
    public List<MarketTopic> list(int page, int limit) {

        MarketTopicExample example = new MarketTopicExample();
        example.createCriteria().andDeletedEqualTo(false);
        example.setOrderByClause("add_time desc");
        PageHelper.startPage(page, limit);
        List<MarketTopic> topicList = marketTopicMapper.selectByExample(example);

        return topicList;
    }

    @Override
    public TopicDetailData queryById(int id) {
        // topic
        MarketTopicExample example = new MarketTopicExample();
        example.createCriteria().andIdEqualTo(id).andDeletedEqualTo(false);
        MarketTopic topic = marketTopicMapper.selectByPrimaryKey(id);
        //获取goodsId
        Integer[] goodsIds = topic.getGoods();
        // goods
        MarketGoodsExample example1 = new MarketGoodsExample();

        if (goodsIds.length>0){
            example1.createCriteria().andDeletedEqualTo(false).andIdIn(Arrays.asList(goodsIds));
        }
        List<MarketGoods> goods = goodsMapper.selectByExample(example1);
        TopicDetailData data = new TopicDetailData();
        data.setGoods(goods);
        data.setTopic(topic);
        return data;
    }

    @Override
    public PageData  queryRelatedList(int id, int page, int limit) {
        // 获取topicId对应的专题中的Goods
        PageHelper.startPage(page,limit);
        MarketTopic marketTopic = marketTopicMapper.selectByPrimaryKey(id);
        List<Integer> list = Arrays.stream(marketTopic.getGoods()).toList();

        List<MarketTopic> marketTopics= new ArrayList<>();
        // 查看所有相同goods的专题
        MarketTopicExample example = new MarketTopicExample();
        for (Integer integer : list) {
            example.createCriteria().andGoodsLike("%"+integer+"%");
            List<MarketTopic> marketTopics1 = marketTopicMapper.selectByExample(example);
           marketTopics = marketTopics1;
        }
        PageData data = PageData.list(marketTopics);
        return data;
    }

}
